package com.wish.banking.controller;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wish.banking.entity.*;
import com.wish.banking.entity.vo.ApplicationscheckVO;
import com.wish.banking.entity.vo.CheckVO;
import com.wish.banking.entity.vo.DetailCfContractVO;
import com.wish.banking.service.*;
import com.wish.banking.utils.BankingUtil;
import com.wish.common.core.usconfig.common.MsgResult;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.HashMap;
import java.util.List;

/**
 * @ClassName:
 * @Description:
 * @Author:caojialin
 * @Date:2022/4/5 16:55
 */
@RestController
@RequestMapping("/applicationsCheck")
public class ApplicationsCheckController {
    @Autowired
    private IJrRentInstallmentService rentInstallmentService;
    @Autowired
    private IJrSfLoanService loanService;
    @Autowired
    private IJrFactoringService factoringService;
    @Autowired
    private IJrFactoringDetailService factoringDetailService;
    @Autowired
    private ICfContractService cfContractService;
    @Autowired
    private IMAttachmentService attachmentService;
    @Autowired
    private ITbBusinessService businessService;
    @Autowired
    private IMCompanyAccountDetailService companyAccountDetailService;
    @Autowired
    private ISfContractService sfContractService;
    @Autowired
    private IJrProductService productService;

    @PostMapping("page")
    public MsgResult page(@RequestBody ApplicationscheckVO applicationscheckVO){
        IPage<ApplicationscheckVO> page = new Page<>(applicationscheckVO.getCurrent(), applicationscheckVO.getSize());
        page = rentInstallmentService.checkPage(page,applicationscheckVO);
        return MsgResult.succeed(page);
    }

    //租房分期
    @GetMapping("installment")
    public MsgResult installment(Long id){
        //租房分期详细信息
        JrRentInstallment installment = rentInstallmentService.getById(id);

        //获取合同基本信息
        DetailCfContractVO contractDetail = cfContractService.detailCfContract(installment.getCfContractId());
        BigDecimal totalMonthLimit= BigDecimal.ZERO;
        BigDecimal monthRent = contractDetail.getMonthRent();
        Integer monthLimit = installment.getMonthLimit();
        // 计算利息
        totalMonthLimit = monthRent.multiply(new BigDecimal(monthLimit));
        // 利息 =应收租约合计* 租客承担比例 / 年化率  * 期数
        // 应收租约合计
        double reLeaseCount = Double.valueOf(installment.getReLeaseCount()).doubleValue();
        // 调用计算公式
        double periods= installment.getMonthLimit();
        //租客承担比例
        double tenantRate = BankingUtil.div(installment.getTenantRate().doubleValue(), 100, 2);// 利率
        // 公寓分期利息合计
        double inInterestCount = Double.valueOf(installment.getInInterestCount()).doubleValue();
        // 计算利息
        double mul = BankingUtil.mul(reLeaseCount, tenantRate);
        double div = BankingUtil.div(mul, 12, 2);
        double rateCount_ = BankingUtil.mul(div, periods);
        double rateCount= BankingUtil.add(rateCount_, inInterestCount);

        QueryWrapper<MAttachment> attachmentQueryWrapper = new QueryWrapper<>();

        //租客合同url
        //租赁合同
        attachmentQueryWrapper.eq("attachment_type",8);
        //出房合同
        attachmentQueryWrapper.eq("relation_type",20);
        //合同id
        attachmentQueryWrapper.eq("relation_id",installment.getCfContractId());
        List<MAttachment> contractUrl = attachmentService.list(attachmentQueryWrapper);

        // 客户身份证复印件
        attachmentQueryWrapper.eq("attachment_type",9);
        List<MAttachment> idCardUrl = attachmentService.list(attachmentQueryWrapper);

        HashMap<String, Object> map = new HashMap<>();
        map.put("contractDetail",contractDetail);
        map.put("totalMonthLimit", totalMonthLimit);
        map.put("contractUrl",contractUrl);
        map.put("idCardUrl",idCardUrl);
        map.put("installment",installment);
        map.put("rateCount",rateCount);

        //获取基本信息
        String bussinessId = installment.getBussinessId();
        TbBusiness business = businessService.getById(bussinessId);
        map.put("business",business);

        // 获取账户类型
        QueryWrapper<MCompanyAccountDetail> companyAccountDetailQueryWrapper = new QueryWrapper<>();
        companyAccountDetailQueryWrapper.eq("business_id",bussinessId);
        companyAccountDetailQueryWrapper.eq("del_flg",0);
        companyAccountDetailQueryWrapper.eq("default_card",1);
        MCompanyAccountDetail companyAccountDetail = companyAccountDetailService.getOne(companyAccountDetailQueryWrapper);
        map.put("companyAccountDetail",companyAccountDetail);

        return MsgResult.succeed(map);
    }

    //收房贷
    @GetMapping("collectmortgage")
    public MsgResult collectmortgage(Long id){
        //获取房贷详细信息
        JrSfLoan loan = loanService.getById(id);
        //获取收房合同详情
        SfContract sfContract = sfContractService.getById(loan.getSfContractId());

        // 承租月租金
        // 周期还款金额  = 还款总额合计 /期数  rp_amount_count/month_limit
        String rpAmountCount = loan.getRpAmountCount();

        double parseDouble = Double.parseDouble(rpAmountCount);

        double cycleAmount= BankingUtil.div(parseDouble, loan.getMonthLimit(), 2);
        //贷款账期期数
        long l = DateUtil.betweenMonth(sfContract.getLeaseStartTime(), sfContract.getLeaseEndTime(), true);
        Integer paymentType = sfContract.getPaymentType();
        long num = l / paymentType;
        if(l%paymentType!=0l){
            num+=1;
        }

        //	BigDecimal monthRent = contractDetail.getMonthRent();
        //	cycleAmount = monthRent.multiply(new BigDecimal(paymentType));
        QueryWrapper<MAttachment> attachmentQueryWrapper = new QueryWrapper<>();

        //查询租业主身份证复印件url
        //收房合同
        attachmentQueryWrapper.eq("relation_type",10);
        //合同id
        attachmentQueryWrapper.eq("relation_id",loan.getSfContractId());
        //业主身份证
        attachmentQueryWrapper.eq("attachment_type",3);
        List<MAttachment> ownerUrl = attachmentService.list(attachmentQueryWrapper);
        //查询收房贷合同url
        attachmentQueryWrapper.eq("attachment_type",2);
        List<MAttachment> sfDContractUrl = attachmentService.list(attachmentQueryWrapper);
        //查询收房贷房产证url
        attachmentQueryWrapper.eq("attachment_type",1);
        List<MAttachment> sfDHouse = attachmentService.list(attachmentQueryWrapper);
        //查询收房贷业主银行卡url
        attachmentQueryWrapper.eq("attachment_type",5);
        List<MAttachment> sfDBank = attachmentService.list(attachmentQueryWrapper);

        HashMap<String, Object> map = new HashMap<>();
        map.put("loan", loan);
        map.put("cycleAmount", cycleAmount);
        map.put("sfContract", sfContract);
        map.put("ownerUrl",ownerUrl);
        map.put("sfDContractUrl",sfDContractUrl);
        map.put("sfDHouse",sfDHouse);
        map.put("sfDBank",sfDBank);
        map.put("num",num);

        //获取基本信息
        String businessId = loan.getBusinessId();
        TbBusiness business = businessService.getById(Long.parseLong(businessId));
        map.put("business",business);

        // 获取账户类型
        QueryWrapper<MCompanyAccountDetail> companyAccountDetailQueryWrapper = new QueryWrapper<>();
        companyAccountDetailQueryWrapper.eq("business_id",businessId);
        companyAccountDetailQueryWrapper.eq("del_flg",0);
        companyAccountDetailQueryWrapper.eq("default_card",1);
        MCompanyAccountDetail companyAccountDetail = companyAccountDetailService.getOne(companyAccountDetailQueryWrapper);
        map.put("companyAccountDetail",companyAccountDetail);

        return MsgResult.succeed(map);
    }

    //应收租约保理
    @GetMapping("leasefactoring")
    public MsgResult leasefactoring(Long id){
        //租约保理详细信息
        QueryWrapper<JrFactoringDetail> factoringDetailQueryWrapper = new QueryWrapper<>();
        factoringDetailQueryWrapper.eq("factoring_id",id);
        List<JrFactoringDetail> factoringDetails = factoringDetailService.list(factoringDetailQueryWrapper);
        JrFactoring factoring = factoringService.getById(id);
        
        //map
        HashMap<String, Object> map = new HashMap<>();
        
        map.put("factoringDetails", factoringDetails);
        map.put("factoring", factoring);

        //获取基本信息
        String businessId = factoring.getBusinessId();
        TbBusiness business = businessService.getById(Long.parseLong(businessId));
        map.put("business",business);

        // 获取账户类型
        QueryWrapper<MCompanyAccountDetail> companyAccountDetailQueryWrapper = new QueryWrapper<>();
        companyAccountDetailQueryWrapper.eq("business_id",businessId);
        companyAccountDetailQueryWrapper.eq("del_flg",0);
        companyAccountDetailQueryWrapper.eq("default_card",1);
        MCompanyAccountDetail companyAccountDetail = companyAccountDetailService.getOne(companyAccountDetailQueryWrapper);
        map.put("companyAccountDetail",companyAccountDetail);

        return MsgResult.succeed(map);
    }

    //应收租约保理详情
    @GetMapping("factoringDetail")
    public MsgResult factoringDetail(Long id){
        //获取保理详情
        JrFactoringDetail factoringDetail = factoringDetailService.getById(id);
        //获取保理申请信息
        JrFactoring factoring = factoringService.getById(factoringDetail.getFactoringId());
        //获取租约信息
        CfContract cfContract = cfContractService.getById(factoringDetail.getCfContractId());

        // 计算  周期还款金额     收款方式的y * 月租金 =  周期还款金额
        BigDecimal cycleAmount= BigDecimal.ZERO;
        //收款方式（押X付Y的Y）
        Integer paymentType = cfContract.getPaymentType();
        // 承租月租金
        BigDecimal monthRent = cfContract.getMonthRent();
        cycleAmount = monthRent.multiply(new BigDecimal(paymentType));

        //计算 实收保理金额  保理授信额度-保理利息 -服务费 （%） = 实收宝理金额
        BigDecimal factoringTrueMoney= BigDecimal.ZERO;
        //  保理授信额度
        BigDecimal factoringCreditMoney = factoringDetail.getFactoringCreditMoney();
        // 保理利息
        BigDecimal factoringInterest = factoringDetail.getFactoringInterest();
        // 服务费 （%）
        BigDecimal serviceFee = factoring.getServiceFee();
        float fee = serviceFee.floatValue();
        //  应收租约金额
        BigDecimal shouldMonthRent = factoringDetail.getShouldMonthRent();
        // 服务费 除  设置默认值百分比
        BigDecimal  feeRent = shouldMonthRent.multiply(new BigDecimal(fee/100));
        BigDecimal  oneServiceFee =feeRent.setScale(2, RoundingMode.HALF_UP);//保留两位小数
        BigDecimal subtract = factoringCreditMoney.subtract(factoringInterest);
        factoringTrueMoney = subtract.subtract(oneServiceFee);

        // 计算 退款金额      应收租约金额- 保理授信额度 =  退款金额
        BigDecimal refundAmount= BigDecimal.ZERO;
        refundAmount = shouldMonthRent.subtract(factoringCreditMoney);

        //查询保理授信比例
        //获取金融产品
        JrProduct product = productService.getById(factoring.getJrProductId());
        //获取授信额度
        Double creditLine = product.getCreditLine();
        double creditLineValue = new BigDecimal(creditLine).setScale(2, RoundingMode.HALF_UP).doubleValue();//保留两位小数


        QueryWrapper<MAttachment> attachmentQueryWrapper = new QueryWrapper<>();
        //出房合同
        attachmentQueryWrapper.eq("relation_type",20);
        //合同id
        attachmentQueryWrapper.eq("relation_id",cfContract.getId());
        //查询租客户身份证复印件url
        attachmentQueryWrapper.eq("attachment_type",9);
        List<MAttachment> jrCardsUrl = attachmentService.list(attachmentQueryWrapper);
        //查询应收租约保理合同url
        attachmentQueryWrapper.eq("attachment_type",8);
        List<MAttachment> jrContractUrl = attachmentService.list(attachmentQueryWrapper);

        HashMap<String, Object> map = new HashMap<>();
        //授信额度
        map.put("creditLine", creditLineValue);
        //周期还款金额
        map.put("cycleAmount", cycleAmount);
        //实收保理金额
        map.put("factoringTrueMoney", factoringTrueMoney);
        //退款金额
        map.put("refundAmount", refundAmount);

        map.put("oneServiceFee", oneServiceFee);
        map.put("jrCardsUrl",jrCardsUrl);
        map.put("jrCardsUrlCount", jrCardsUrl.size());
        map.put("jrContractUrl",jrContractUrl);
        map.put("jrContractUrlCount",jrContractUrl.size());
        map.put("cfContract", cfContract);
        map.put("factoring", factoring);
        map.put("factoringDetail", factoringDetail);

        return MsgResult.succeed(map);
    }

    //审核状态修改
    @PostMapping("checks")
    public MsgResult checks(@RequestBody CheckVO checkVO){
        Integer productType = checkVO.getProductType();
        //租房分期
        if(productType ==1){
            JrRentInstallment jrRentInstallment = new JrRentInstallment();
            jrRentInstallment.setId(checkVO.getCheckId());
            jrRentInstallment.setApplyState(checkVO.getApplyState());
            if(StringUtils.isNotEmpty(checkVO.getAuditMemo()))
                jrRentInstallment.setAuditMemo(checkVO.getAuditMemo());
            rentInstallmentService.updateById(jrRentInstallment);
        }
        //收房贷
        if (productType == 2){
            JrSfLoan jrSfLoan = new JrSfLoan();
            jrSfLoan.setId(checkVO.getCheckId());
            jrSfLoan.setApplyState(checkVO.getApplyState());
            if(StringUtils.isNotEmpty(checkVO.getAuditMemo()))
                jrSfLoan.setAuditMemo(checkVO.getAuditMemo());
            loanService.updateById(jrSfLoan);
        }
        //应收租约保理
        if (productType == 3){
            JrFactoring jrFactoring = new JrFactoring();
            jrFactoring.setId(checkVO.getCheckId());
            jrFactoring.setApplyState(checkVO.getApplyState());
            if(StringUtils.isNotEmpty(checkVO.getAuditMemo()))
                jrFactoring.setAuditMemo(checkVO.getAuditMemo());
            factoringService.updateById(jrFactoring);
        }
        return MsgResult.succeed();
    }

}
